package config

import (
	"io/fs"
	"os"
	"strings"

	"cloudea.com/container/utils"
)

var HOME_PATH = os.Getenv("HOME") + "/.container"
var IMAGE_PATH = HOME_PATH + "/images"       // 保存镜像的目录
var CONTA_PATH = HOME_PATH + "/containers"   // 保存容器的目录
var LAYER_PATH = HOME_PATH + "/layers"       // 保存overlay2的目录
var CONFIG_PATH = HOME_PATH + "/config.json" // 配置文件路径
var TEMP_PATH = "/tmp/container"             // 下载镜像的临时解压目录
var MANIFEST = "manifest.json"
var DOCKER_HUB = "https://qvcfrypn.mirror.aliyuncs.com"
var CONTAINER0 = "container0"
var CONTAINER0_CIDR = "10.0.0.0/8"
var CPU_PERIOD = 100000 // cpu时间片分配周期为100ms

/** 镜像根目录 */
func GetImageBase(name string, tag string) string {
	path := IMAGE_PATH + "/" + name + "/" + tag
	os.MkdirAll(path, fs.ModePerm)
	return path
}

/** 镜像配置文件 */
func GetImageConfig(name string, tag string) string {
	return GetImageBase(name, tag) + "/" + MANIFEST
}

/** 镜像容器目录 */
func GetImageContainers(name string, tag string) string {
	path := GetImageBase(name, tag) + "/containers"
	os.MkdirAll(path, fs.ModePerm)
	return path
}

/** 获取镜像容器位置  **/
func GetImageContainer(name string, tag string, containerName string) string {
	return GetImageContainers(name, tag) + "/" + containerName
}

/** 镜像层所在位置  */
func GetImageLayerBase(blobSum string) string {
	path := LAYER_PATH + "/" + strings.Replace(blobSum, ":", "", 1)
	os.MkdirAll(path, fs.ModePerm)
	return path
}

/** 获取压缩文件名 */
func GetImageTar(blobSum string) string {
	return TEMP_PATH + "/" + blobSum + ".tar"
}

/** 获取容器的目录 */
func GetContainerBase(name string) string {
	path := CONTA_PATH + "/" + name
	os.MkdirAll(path, fs.ModePerm)
	return path
}

/** 获取容器的配置文件 */
func GetContainerConfig(name string) string {
	return GetContainerBase(name) + "/" + MANIFEST
}

/** 获取容器的Cgroup */
func GetContainerCgroup(name string) string {
	configFile := GetContainerConfig(name)
	if !utils.FileExists(configFile) {
		panic("必需是已存在的容器")
	}
	containerCgroupPath := "/sys/fs/cgroup/container"
	containerSubTree := containerCgroupPath + "/cgroup.subtree_control"
	if !utils.FileExists(containerCgroupPath) {
		os.MkdirAll(containerCgroupPath, fs.ModePerm)
		utils.Shell("echo '+cpu +memory' > " + containerSubTree)
	}
	containerPrivateCgroupPath := "/sys/fs/cgroup/container/" + name
	if !utils.FileExists(containerPrivateCgroupPath) {
		os.MkdirAll(containerPrivateCgroupPath, fs.ModePerm)
	}
	return containerPrivateCgroupPath
}

func init() {
	// 创建保存容器和镜像的目录
	err := os.MkdirAll(HOME_PATH, fs.ModePerm)
	if err != nil {
		panic(err)
	}
	os.MkdirAll(IMAGE_PATH, fs.ModePerm)
	os.MkdirAll(CONTA_PATH, fs.ModePerm)
	os.MkdirAll(LAYER_PATH, fs.ModePerm)
	os.MkdirAll(TEMP_PATH, fs.ModePerm)
}
